<?php
declare (strict_types=1);

namespace app\exam\logic\admin;

use app\common\exception\LogicException;
use app\exam\model\admin\Popup as PopupModel;

/**
 * Class Popup
 *
 * @package app\exam\logic\admin
 */
class Popup
{
    /**
     * 设置题库
     *
     * @param string $dataType
     * @param int    $dataId
     * @param array  $bankIds
     * @return Popup|array|\think\Model|void
     */
    public static function set(string $dataType, int $dataId, array $bankIds)
    {

        $popup = PopupModel::where('data_type', $dataType)
            ->where('data_id', $dataId)
            ->findOrEmpty();

        // 为空时需要追加的字段
        if ($popup->isEmpty()) {
            $popup->data_type = $dataType;
            $popup->data_id   = $dataId;
        }

        $popup->bank_ids = $bankIds;

        if (!$popup->save()) {
            throw new LogicException('设置失败');
        }

        return $popup;
    }

    /**
     * 获取设置的题库
     *
     * @param string $dataType
     * @param int    $dataId
     * @return array|mixed
     */
    public static function get(string $dataType, int $dataId)
    {
        $popup = PopupModel::where('data_type', $dataType)
            ->where('data_id', $dataId)
            ->findOrEmpty();

        $bankIds = $popup->isEmpty() ? [] : $popup->getAttr('bank_ids');
        $ret     = [];
        if ($bankIds) {
            $bankInfos = \app\exam\model\admin\QuestionBank::withoutGlobalScope(['mhm'])->whereIn('id', $bankIds)->field([
                'id' => 'value',
                'title'
            ])->select();

            if (!$bankInfos->isEmpty()) {
                $ret = $bankInfos->toArray();
            }
        }

        return $ret;
    }

}
